#!/usr/bin/perl

####################################################
# Copyright (c) 2002-2007 BioWare Corp.
# http://www.bigdaddymonitor.org
#
# This file is part of the BigDaddy Monitoring
# program. It is free software distributed under
# the terms of the BSD License. It is ditributed
# in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY; without event the implied
# warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# The BSD License is available from:
# http://www.opensource.org/licenses/bsd-license.php
####################################################

#===================================================================================================
# BigDaddy External Monitor version 3.0
# Main Monitor for all External Monitoring modules for Servers
# Dups 27.03.2004
# Dups 14.04.2006 <dups@bioware.com>
#===================================================================================================

BEGIN
{
	push(@INC,'/bigdaddy')
}


use strict;
use POSIX;
use DBI;
use Config::IniFiles;
use BioMain qw(:allfunctions);
use Time::Local;

my $logFile="/bigdaddy/logs/server_monitor.log";
my $processFile="/bigdaddy/logs/server_monitor.process";
check_logfile($logFile, "Server Main");

#Before we do anything we are going to bring up the main ini file: bigdaddy.ini should be in the
#same dir as these executables.
my $bigdaddy_cfg= new Config::IniFiles( -file => "/bigdaddy/bigdaddy.ini" );

my $this_process_name = $bigdaddy_cfg->val('main', 'thisprocessname');

my $dbIniHandle;

#Get the processing configuration
my $bdprocessing = $bigdaddy_cfg->val('main', 'bdprocessing');

#Get the dbini handle
#This is dependent on what kind of process is running
if ($bdprocessing eq "single" || $bdprocessing eq "multimaster")
{
	
	$dbIniHandle = $bigdaddy_cfg->val('main', 'dbinihandle');
}
elsif ($bdprocessing eq "masterslave")
{
	if ($bigdaddy_cfg->val('masterslave', 'thisinstance') eq "master")
	{
		$dbIniHandle = $bigdaddy_cfg->val('masterslave', 'masterdbhandle');
	}
	
	if ($bigdaddy_cfg->val('masterslave', 'thisinstance') eq "slave")
	{
		$dbIniHandle = $bigdaddy_cfg->val('masterslave', 'slavedbhandle');
	}
}



#Require the common Bigdaddy functions etc.
require ("/bigdaddy/bigdaddy_common.pl");


#Get the mailserver
my $mailServer = $bigdaddy_cfg->val('main', 'smtpserver');

if (!defined($mailServer) || $mailServer eq '')
{
	$mailServer = "localhost";
}

#Get the Global From Email
my $fromEmail = $bigdaddy_cfg->val('main', 'fromemail');



my ($start_val) = @ARGV;

#===================================================================================================
# Main
#===================================================================================================
if ($start_val eq "stop")
{
	system ("killall bd_monitor > /dev/null 2>&1");
	exit;

}




&daemonize;
#make a child

my $dbb1 = callfor_db_handle($dbIniHandle, 0, 99);

my $sql="UPDATE server SET last_monenabled=".time()." WHERE active=1";
$dbb1->do($sql);
$dbb1->disconnect;



my $bReturn;
my $nScriptRunTime;

START: while(1)
{
	
	my $crontabIni="servermon";
	my $sID = "servermon";
	my $nStartTime=time();
	
	#===================================================================================================
	# Processing configuration
	#===================================================================================================
	if ($bdprocessing ne "single")
	{
		if ($bdprocessing eq "masterslave")
		{
			$bReturn = CheckMasterSlave($bigdaddy_cfg, $sID);
		}
		
		if ($bdprocessing eq "multimaster")
		{
			$bReturn = CheckMultiMaster($bigdaddy_cfg, $dbIniHandle, $this_process_name, $sID);
		}
			
		if ($bReturn == 1)
		{
			#logEntry("Returned To Start", $logFile, 0);
			$nScriptRunTime = time() - $nStartTime;
			#Open a Log File and write in the current status on this server
			&SetProcessTime($processFile);
			sleep(60 - $nScriptRunTime);
			goto START;
		}
		
		if ($bReturn == 2)
		{
			#logEntry("Continuing", $logFile, 0);
			goto CONTINUE;
		}

	}
	
	CONTINUE: 
	
	my $dbb = callfor_db_handle($dbIniHandle, 0, 99);
	
	#Database Reporting
	my $sql="UPDATE report SET report='".time()."', processID = '".$this_process_name."' WHERE ID='".$sID."'";
	$dbb->do( $sql );
	
	#Open a Log File and write in the current status on this server
	&SetProcessTime($processFile);
	
	
	

	$sql="SELECT inifile, ID FROM inifile WHERE ID IN ('".$crontabIni."')";
	#print $sql."\n";
	my $result=$dbb->prepare( $sql );
	$result->execute;

	while (my $ref=$result->fetchrow_hashref())
	{
	    open (TMPINIFILE, ">/tmp/exmon".$ref->{'ID'}.".ini") or die "Could not open temp file for writing: $!";
	    print TMPINIFILE $ref->{'inifile'};
	    close (TMPINIFILE) or die "Could not close temp file: $!";
	}

	my $cfg_crontab= new Config::IniFiles( -file => "/tmp/exmon".$crontabIni.".ini" );

	# Check for the crontab delay value
	my $delay=$cfg_crontab->val('global','globaldelay');
	my $status=$cfg_crontab->val('global','globalstatus');




	if ($status eq "off" || ($status eq "delay" && $delay>time()))
	{
		#continue don't start up monitoring
		#Do any processing of off stuff
	}
	else
	{
		$sql="SELECT ID FROM server WHERE active=1";
		my $result=$dbb->prepare($sql);
		$result->execute;

		while (my $ref=$result->fetchrow_hashref())
		{
			&makeNewChild($ref->{'ID'});
		}
	}

	#We only want to run this a minimum of every 60 seconds.
	$nScriptRunTime=time()-$nStartTime;

	#Update the report table.

	$dbb->disconnect;
	if ($nScriptRunTime<60)
	{
		sleep(60-$nScriptRunTime);
	}
}

#===================================================================================================
# Child Subroutine
# Forks child for each server
#===================================================================================================
sub makeNewChild
{

	my ($serverID) = @_;
	my $sql;
	my $pid;
	#my $logFile="/bigdaddy/logs/server_monitor.log";
	#check_logfile($logFile, "Server Child");
	die "fork: $!" unless defined ($pid = fork);

	if ($pid)
	{
		#parent process records the birth of the child and returns to the rest of the script
		#$children[$number]=$pid;
		#$SIG{CHLD} = 'IGNORE';
		#return;

		my $kid;
		do {
			$kid = waitpid($pid, &WNOHANG);
		} until $kid > 0;
		return;
	}
	else
	{
		#First to check if the servers are being monitored at all....
		#Create the database handle with no idle and no crash on errors
		my $dbh = callfor_db_handle($dbIniHandle, 0, 99);

		$sql="SELECT ID, hostname, last_externalcheck, last_monenabled,
				iniID, mon_externalreport, mon_currentlevel,
				mon_endlevel, mon_threshold, mon_currentlevelstart, mon_lastcheck, mon_startlevel
			FROM server
			WHERE ID=".$serverID;
		#print $sql."\n";
		my $result=$dbh->prepare($sql);
		$result->execute;
		
		#Get the Phone Tags
		my %phoneTags;
		%phoneTags = get_phoneTags($dbh);

		my $delaystatus=0;

		while (my $ref=$result->fetchrow_hashref())
		{
			my $useTimeForCheck;
			my $serverReportThreshold=1200;
			#is ranenabled-time() greater than mon_threshold
			if ($ref->{'last_monenabled'}>$ref->{'last_externalcheck'})
			{
				$useTimeForCheck=$ref->{'last_monenabled'};
			}
			else
			{
				$useTimeForCheck=$ref->{'last_externalcheck'};
			}

			my $thresholdValExt=time()-$useTimeForCheck;

			
			my $cfg=get_inicfg( $ref->{'iniID'}, $serverID, $dbh );

			#Check to see if this is a time for the server not to be monitored.
			#if so simply set it delayed and quickly escape out of here.
			my $delaystart=$cfg->val('global','tempdelaystart');
			my $delayend=$cfg->val('global','tempdelayend');
			
			if ($delaystart ne '' && $delayend ne '')
			{

				$delaystatus=checkTempDelay($delaystart, $delayend);
				
				if ($delaystatus>0)
				{
					setServerDelay($delaystatus, $serverID, $dbh);
					goto DONE;
				}
			}
			
			#Delay Check Second Time around
			#Check to see if this is a time for the server not to be monitored.
			#if so simply set it delayed and quickly escape out of here.
			$delaystart=$cfg->val('global','tempdelaystart2');
			$delayend=$cfg->val('global','tempdelayend2');
			
			if ($delaystart ne '' && $delayend ne '')
			{
				$delaystatus=checkTempDelay($delaystart, $delayend);

				if ($delaystatus>0)
				{
					setServerDelay($delaystatus, $serverID, $dbh);
					goto DONE;
				}
			}

			if (($thresholdValExt>$serverReportThreshold && $ref->{'last_externalcheck'}>0 && $ref->{'mon_externalreport'}==1))
			{
				#We know now that this Cron is having a problem.
				#We need to get the cron ini


				# Is the currentlevel 0?
				if ($ref->{'mon_currentlevel'}==0)
				{
					&doaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'mon_startlevel'}, $dbh, $this_process_name, %phoneTags);
					&updateinfo( $serverID, $dbh, $ref->{'mon_startlevel'} );
				}

				# If the currentlevel is greater than 0
				if ($ref->{'mon_currentlevel'}>0)
				{
					#is this the final level?
					if ($ref->{'mon_currentlevel'}==5 || $ref->{'mon_currentlevel'}==$ref->{'mon_endlevel'})
					{
						#is it time to loop
						if ((time()-600)>$ref->{'mon_lastcheck'})
						{
							&doaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'mon_currentlevel'}, $dbh, $this_process_name, %phoneTags);
							&setlastcheck($serverID, $dbh);
						}
					}
					else
					{
						#It's not the final level so check to see if it is time to escalate
						my $level="level".$ref->{'mon_currentlevel'};
						my $escalateTime=0;
						my $loopTime=0;

						if (defined($cfg->val( $level, 'escalate' )))
						{
							$escalateTime=$cfg->val( $level, 'escalate' );
						}

						if (defined($cfg->val( $level, 'loop' )))
						{
							$loopTime=$cfg->val( $level, 'loop' );
						}

						#&logEntry("Loop: $loopTime Escalate: $escalateTime", $logFile, 0);

						if ((time()-$escalateTime)>$ref->{'mon_currentlevelstart'})
						{
							#Time to escalate
							&doaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, ($ref->{'mon_currentlevel'}+1), $dbh, $this_process_name, %phoneTags);
							&updateinfo( $serverID, $dbh, ($ref->{'mon_currentlevel'}+1));
						}
						elsif ((time()-$loopTime)>$ref->{'mon_lastcheck'})
						{
							#&logEntry("I say again: Loop: $loopTime Escalate: $escalateTime", $logFile, 0);
							#Time to Loop
							&doaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'mon_currentlevel'}, $dbh, $this_process_name, %phoneTags);
							&setlastcheck($serverID, $dbh);
						}
					}
				}
			}
			else
			{
				$sql="UPDATE server SET mon_currentlevel=0, mon_currentlevelstart=0, mon_lastcheck=0 WHERE ID=".$serverID;
				#print $sql."\n";
				$dbh->do( $sql );
			}
		} #end while

		#Second Check the server modules for errors
		$sql="SELECT sm.*, m.type, m.name, m.runfrom, s.hostname, s.last_monenabled
			FROM server_module sm
			LEFT JOIN module m ON m.ID=sm.moduleID
			LEFT JOIN server s ON s.ID=sm.serverID
			WHERE sm.serverID=".$serverID."
				AND sm.active=1";
		$result=$dbh->prepare($sql);
		$result->execute;

		while (my $ref=$result->fetchrow_hashref())
		{
			my $useTimeToCheckFrom;
			my $sEmailParams;
			
			#Create the Param String to be added to the subject line for those modules that should show the
			#Parameters e.g. TCP Port (25)
			$sEmailParams = $ref->{'parameters'};
			$sEmailParams =~ s/\[hostname\]//gi;
			$sEmailParams =~ s/^\s+//;
			$sEmailParams =~ s/\s+$//;
			
			if ($sEmailParams ne "")
			{
				$sEmailParams = " (".$sEmailParams.")";
			}

			
			if ($ref->{'last_monenabled'}>$ref->{'mon_lastreport'})
			{
				$useTimeToCheckFrom=$ref->{'last_monenabled'};
			}
			elsif ($ref->{'last_monmodenabled'}>$ref->{'mon_lastreport'})
			{
				$useTimeToCheckFrom=$ref->{'last_monmodenabled'};
			}
			else
			{
				$useTimeToCheckFrom=$ref->{'mon_lastreport'};
			}

			my $noProblems=0;
			my $doProblemProcessing=0;
			my $reportValue;
			my $reportLevel;
			#First of is this type boolean?
			if ($ref->{'type'}==1 && $ref->{'mon_lastreport'}>=$useTimeToCheckFrom && $ref->{'lastreport'} ne "1")
			{
				$doProblemProcessing=1;
				goto PROBLEM;
			} #end boolean processing
			else
			{
				$noProblems=1;
			}

			#non-boolean processing
			if ($ref->{'type'}==2 && $ref->{'mon_lastreport'}>=$useTimeToCheckFrom)
			{
				while ($ref->{'lastreport_threshold'} =~ m/level(.*?):([\.0-9]+)/gi)
				{
					if ($ref->{'lastreport'}>$2)
					{
						#there is an error
						$doProblemProcessing=1;
						$reportValue=$ref->{'lastreport'};
						$reportLevel=$1;
						goto PROBLEM;
					}
				}

				$noProblems=1;
			}

			if ($noProblems==1)
			{
				$sql="UPDATE server_module SET mon_currentlevel=0, mon_currentlevelstart=0, mon_lastcheck=0 WHERE ID=".$ref->{'ID'};
				#print $sql."\n";
				$dbh->do( $sql );
			}

			PROBLEM: if ($doProblemProcessing==1)
			{
				#there is an error.
				#We know now that this Module is having a problem.
				#We need to get the module ini
				my $cfg=get_inicfg( $ref->{'iniID'}, $serverID, $dbh );

				# Is the currentlevel 0?
				if ($ref->{'mon_currentlevel'}==0)
				{
					my $doLevel;
					if (defined($reportLevel))
					{
						$doLevel=$reportLevel;
					}
					else
					{
						$doLevel=$ref->{'mon_startlevel'};
					}


					&domodaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'name'}.$sEmailParams, $reportValue, $doLevel, $dbh, $this_process_name, %phoneTags);
					&updatemodinfo( $ref->{'ID'}, $dbh, $doLevel );
				}

				# If the currentlevel is greater than 0
				if ($ref->{'mon_currentlevel'}>0)
				{

					if ($cfg->val('global','escalate') eq "no" || $ref->{'mon_currentlevel'}==5 || $ref->{'mon_currentlevel'}==$ref->{'mon_endlevel'} || defined($reportValue))
					{
						my $loopTime;

						my $doLevel;
						if (defined($reportLevel))
						{
							$doLevel=$reportLevel;
						}
						else
						{
							$doLevel=$ref->{'mon_currentlevel'};
						}

						if ($cfg->val('global','escalate') eq "no")
						{
							$loopTime=$cfg->val('global','loop');
						}
						else
						{
							$loopTime=$cfg->val("level".$doLevel,"loop");
						}

						if ($loopTime==0 || !defined($loopTime))
						{
							$loopTime=600;
						}

						#there is to be no escalation
						#is it time to loop
						if ((time()-$loopTime)>$ref->{'mon_lastcheck'})
						{
							&domodaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'name'}.$sEmailParams, $reportValue, $doLevel, $dbh, $this_process_name, %phoneTags);

							if (defined($reportLevel))
							{
								&updatemodinfo( $ref->{'ID'}, $dbh, $doLevel );
							}

							&setmodlastcheck($ref->{'ID'}, $dbh);
						}
					}
					else
					{

						#It's not the final level and we are allowed to escalate so check to see if it is time to escalate
						my $level="level".$ref->{'mon_currentlevel'};
						my $escalateTime=0;
						my $loopTime=0;
						if (defined($cfg->val( $level, 'escalate' )))
						{
							$escalateTime=$cfg->val( $level, 'escalate' );
						}

						if (defined($cfg->val( $level, 'loop' )))
						{
							$loopTime=$cfg->val( $level, 'loop' );
						}

						if ((time()-$escalateTime)>$ref->{'mon_currentlevelstart'})
						{
							#Time to escalate
							&domodaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'name'}.$sEmailParams, $reportValue, $ref->{'mon_currentlevel'}+1, $dbh, $this_process_name, %phoneTags);
							&updatemodinfo( $ref->{'ID'}, $dbh, $ref->{'mon_currentlevel'}+1 );

						}
						elsif ((time()-$loopTime)>$ref->{'mon_lastcheck'})
						{
							#Time to Loop
							&domodaction( $ref->{'iniID'}, $serverID, $ref->{'hostname'}, $ref->{'name'}.$sEmailParams, $reportValue, $ref->{'mon_currentlevel'}, $dbh, $this_process_name, %phoneTags);
							&setmodlastcheck($ref->{'ID'}, $dbh);
						}
					}
				}
			}


		} #end while
		DONE:exit;
	} #end if
} #end sub


#===================================================================================================
# updateinfo(int $serverID, dbh $dbj, int $levelup)
# Updates the info for a server to go up a level, sets the time for the level start
# And the lastcheck value which tracks when an action was last performed
#===================================================================================================
sub updateinfo
{
	my ($serverID, $dbh, $levelup)=@_;
	my $sql="UPDATE server SET mon_currentlevel='".$levelup."', mon_currentlevelstart=".time().", mon_lastcheck=".time()." WHERE ID=".$serverID;
	$dbh->do( $sql );
}

#===================================================================================================
# updatemodinfo(int $serverID, in $moduleID, dbh $dbj, int $levelup)
# Updates the info for a server to go up a level, sets the time for the level start
# And the lastcheck value which tracks when an action was last performed
#===================================================================================================
sub updatemodinfo
{
	my ($ID, $dbh, $levelup)=@_;
	my $sql="UPDATE server_module SET mon_currentlevel='".$levelup."', mon_currentlevelstart=".time().", mon_lastcheck=".time()." WHERE ID=".$ID;
	$dbh->do( $sql );
}

#===================================================================================================
# setlastcheck(int $serverID, dbh $dbh)
# Sets only the last check value of when actions were performed for server ID
#===================================================================================================
sub setlastcheck
{
	my ($serverID, $dbh) = @_;
	my $sql="UPDATE server SET mon_lastcheck=".time()." WHERE ID=".$serverID;
	$dbh->do( $sql );
}

#===================================================================================================
# setlastcheck(int $serverID, int moduleID dbh $dbh)
# Sets only the last check value of when actions were performed for server ID
#===================================================================================================
sub setmodlastcheck
{
	my ($ID, $dbh) = @_;
	my $sql="UPDATE server_module SET mon_lastcheck=".time()." WHERE ID=".$ID;
	$dbh->do( $sql );
}

#===================================================================================================
# doaction(str iniID, int $serverID, str $hostName, int $level, dbh $dbh)
# So the actions specified in the ini for this level, this server
#===================================================================================================
sub doaction
{
	my ($iniID, $serverID, $hostName, $level, $dbh, $this_process_name, %phoneTags) = @_;
	#Get the current time string
	my $sTimeString = localtime;
	
	my $cfg=get_inicfg( $iniID, $serverID, $dbh );
	
	my $bUseTags;
	#Check to see if this ini file uses tags or email addresses
	if (defined($cfg->val( 'global','usetags' )) && $cfg->val( 'global','usetags' ) eq "yes")
	{
		$bUseTags = 1;
	}
	
	#print $cfg->val( "level".$level,'email' )."\n";
	if (defined($cfg->val( "level".$level,'email' )))
	{
		my $messageString="Monitoring fail on server / Level: ".$level."\n";
		if (defined($cfg->val( "level".$level,'message' )))
		{
			$messageString.=$cfg->val( "level".$level,'message' );
		}
		$messageString.="\n".$sTimeString;
		$messageString.= "BigDaddy Process: ".$this_process_name."\n";
		
		my $subjectString = "BD".$level." - ".$hostName;
		logEntry("Action Performed: ".$subjectString, $logFile, 0);
		
		my @emailTags;
		
		if ($bUseTags == 1)
		{
			@emailTags = split(/,/, $cfg->val( "level".$level,'email' ));
			
			for (my $i = 0; $i<scalar(@emailTags); $i++)
			{
				my $sEmail = $phoneTags{trim($emailTags[$i])};
				&send_mail($sEmail, $messageString, $subjectString, $fromEmail, $mailServer  );
			}
		}
		else
		{
			&send_mail($cfg->val( "level".$level,'email' ), $messageString, $subjectString, $fromEmail, $mailServer  );
		}
	}
}


#===================================================================================================
# domodaction(str iniID, int $serverID, str $hostName, str ModuleName, int $level, dbh $dbh)
# So the actions specified in the ini for this level, this server
#===================================================================================================
sub domodaction
{
	my ($iniID, $serverID, $hostName, $modName, $reportValue, $level, $dbh, $this_process_name, %phoneTags) = @_;
	my $cfg=get_inicfg( $iniID, $serverID, $dbh );
	#Get the current time string
	my $sTimeString = localtime;
	#print $cfg->val( "level".$level,'email' )."\n";
	
	my $bUseTags;
	#Check to see if this ini file uses tags or email addresses
	if (defined($cfg->val( 'global','usetags' )) && $cfg->val( 'global','usetags' ) eq "yes")
	{
		$bUseTags = 1;
	}
	
	if (defined($cfg->val( "level".$level,'email' )))
	{
		my $messageString=$modName." / Level: ".$level."\n";
		if (defined($reportValue))
		{
			$messageString.="Threshold Passed : ".$reportValue."\n";
		}

		if (defined($cfg->val( "level".$level,'message' )) && $cfg->val( "level".$level,'message' ) ne '')
		{
			$messageString.=$cfg->val( "level".$level,'message' )."\n";;
		}
		
		$messageString.= $sTimeString."\n";
		$messageString.= "BigDaddy Process: ".$this_process_name."\n";
		
		my $subjectString = "BD".$level." - ".$hostName." - ".$modName;
		
		#logEntry("Action Performed: ".$subjectString, $logFile, 0);
		
		my @emailTags;
		
		if ($bUseTags == 1)
		{
			@emailTags = split(/,/, $cfg->val( "level".$level,'email' ));
			
			for (my $i = 0; $i<scalar(@emailTags); $i++)
			{
				
				my $sEmail = $phoneTags{trim($emailTags[$i])};
				#logEntry("Email To: ".$sEmail." Line is ".$cfg->val( "level".$level,'email' )." Tag is: ".$emailTags[$i], $logFile, 0);
				&send_mail($sEmail, $messageString, $subjectString, $fromEmail, $mailServer  );
			}
		}
		else
		{
			&send_mail($cfg->val( "level".$level,'email' ), $messageString, $subjectString, $fromEmail, $mailServer );
		}
	}
}



#===================================================================================================
# get_inicfg(str iniID, int cronID, dbh dbh)
# Gets the inifile for that cron
#===================================================================================================
sub get_inicfg
{
	my ($iniID, $serverID, $dbh) = @_;
	my $sql="SELECT inifile, ID FROM inifile WHERE ID='".$iniID."'";
	my $result=$dbh->prepare( $sql );
	$result->execute;

	my $filenameAdd="serverID".$serverID."_".time();
	my $inifileName;
	while (my $ref=$result->fetchrow_hashref())
	{
		$inifileName="/tmp/".$ref->{'ID'}.".ini.".$filenameAdd;
		open (TMPINIFILE, ">$inifileName") or die "Could not open temp file for writing: $!";
		print TMPINIFILE $ref->{'inifile'};
		close (TMPINIFILE) or die "Could not close temp file: $!";
	}

	my $cfg= new Config::IniFiles( -file => $inifileName );
	unlink($inifileName);
	return $cfg;
}

#===================================================================================================
# checkTempDelay(str delaystart, str delayend)
# Checks to see if current time is between the temp delays spec
#===================================================================================================
sub checkTempDelay
{
	my ($delaystart, $delayend) = @_;

	my $starthour;
	my $startmin;
	my $endhour;
	my $endmin;

	if ($delaystart =~ m/([0-9]+):([0-9]+)/)
	{
		$starthour=$1;
		$startmin=$2;
	}

	if ($delayend =~ m/([0-9]+):([0-9]+)/)
	{
		$endhour=$1;
		$endmin=$2;
	}

	my $startstamp= timelocal(0,$startmin,$starthour,(localtime)[3,4,5]);
	my $endstamp= timelocal(0,$endmin,$endhour,(localtime)[3,4,5]);

	my $currentTime=time();
	if ($currentTime>$startstamp && $currentTime<$endstamp)
	{
		return $endstamp;
	}
	else
	{
		return 0;
	}
}

#===================================================================================================
# get_phoneTags
# Gets the phone tags and places them into a hash
#===================================================================================================
sub get_phoneTags
{
	my ($dbh) = @_;
	my %hash;
	
	my $sql="SELECT ID, phoneNumber FROM phoneTag";
	my $result=$dbh->prepare( $sql );
	$result->execute;
	while (my $ref=$result->fetchrow_hashref())
	{
		$hash{$ref->{'ID'}} = $ref->{'phoneNumber'};
	}
	
	return %hash;
}
#===================================================================================================
# setServerDelay
# Gets the phone tags and places them into a hash
#===================================================================================================
sub setServerDelay
{
	my ($delaystatus, $serverID, $dbh) = @_;
	my $sql="UPDATE server SET active=2, delayed_until='".$delaystatus."'  WHERE ID='".$serverID."'";
	$dbh->do($sql);

	$sql="UPDATE server_module SET active=2, delayed_until='".$delaystatus."'  WHERE serverID='".$serverID."' AND active=1";
	$dbh->do($sql);
}


